package com.gxa.learning.pc.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.common.JsonResult;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.pojo.Course;
import com.gxa.learning.core.pojo.CourseForMain;
import com.gxa.learning.core.pojo.LevelManager;
import com.gxa.learning.core.pojo.Type;
import com.gxa.learning.core.util.JsonUtil;
import com.gxa.learning.core.util.StringUtil;
import com.gxa.learning.pc.service.CourseService;
import com.gxa.learning.pc.service.LevelManagerService;
import com.gxa.learning.pc.service.MainService;
import com.gxa.learning.pc.service.TypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 操作课程的接口
 *
 * @Author ChenJ
 * @date 2021/12/02 16:11
 **/
@RestController
@RequestMapping("/course")
@Api(value = "CourseController", tags = "操作课程的接口")
public class CourseController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private MainService mainService;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private LevelManagerService levelManagerService;
    @Autowired
    private TypeService typeService;

    @PostMapping("/insert")
    @ApiOperation("添加课程的接口")
    @ApiImplicitParam(name = "course", value = "course", paramType = "body", dataType = "Course", dataTypeClass = Course.class)
    @Transactional
    public Map<String, Object> insert(@RequestBody Course course) throws BusinessException {

        // 写一点东西

        // 校验是否是合格的对象
        if (course == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }
        course.setStatus(true);
        Course insert = courseService.insert(course);

        ValueOperations<String, Object> stringObjectValueOperations = redisTemplate.opsForValue();
        stringObjectValueOperations.set("course" + insert.getId(), JsonUtil.objectToString(insert));

        Map<String, Object> map = new HashMap<>(16);
        if (insert.getStatus() != null) {
            if (insert.getStatus()) {
                Map<String, String> typeAndLevel = courseService.getTypeAndLevel(insert.getId());
                map.put("id", insert.getId());
                map.put("status", insert.getStatus());
                map.put("title", insert.getTitle());
                map.put("cover", insert.getCover());
                map.put("type", typeAndLevel.get("type_name"));
                map.put("level", typeAndLevel.get("level_manager_level"));
                map.put("explain", insert.getExplain());
                System.out.println("map:" + map);
            }
        }

        mainService.incrCourseScore(map);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/select")
    @ApiOperation("获取课程列表的接口（包含模糊查询）")
    @ApiImplicitParam(name = "map", value = "map", dataType = "Map", paramType = "body")
    public Map<String, Object> select(@RequestBody Map<String, Object> map) throws BusinessException, ParseException {

        System.out.println("map:"+map);

        // 加点东西

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if (map == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }
        Map<String, Object> course2 = (Map<String, Object>) map.get("course");
        System.out.println("course2:"+course2);
        Course course = new Course();

        if (course2 != null) {
            if (course2.get("id") != null) {
                course.setId(Long.valueOf(course2.get("id").toString()));
            }
            if (course2.get("cover") != null) {
                course.setCover(course2.get("cover").toString());
            }
            if (course2.get("typeId")!=null) {
                course.setTypeId(Long.valueOf(course2.get("typeId").toString()));
            }
            if (course2.get("lmId")!=null) {
                course.setLmId(Long.valueOf(course2.get("lmId").toString()));
            }
            if (course2.get("title") != null) {
                course.setTitle(course2.get("title").toString());
            }
//            if (!StringUtil.isEmpty(course2.get("status").toString())) {
            if (course2.get("status")!=null) {
                course.setStatus(Boolean.valueOf(course2.get("status").toString()));
            }
            if (course2.get("explain") != null) {
                course.setExplain(course2.get("explain").toString());
            }
            if (course2.get("finishTime") != null) {
                course.setFinishTime(simpleDateFormat.parse(course2.get("finishTime").toString()));
            }
            if (course2.get("ware") != null) {
                course.setWare(Integer.valueOf(course2.get("ware").toString()));
            }
            if (course2.get("accessory") != null) {
                course.setAccessory(course2.get("accessory").toString());
            }
            if (course2.get("rule") != null) {
                course.setRule(course2.get("rule").toString());
            }
            if (course2.get("admin") != null) {
                course.setAdmin(course2.get("admin").toString());
            }
            if (course2.get("projectId") != null) {
                course.setProjectId(Long.valueOf(course2.get("projectId").toString()));
            }
        }

        // 先定义
        PageInfo<Course> coursePageInfo = null;

        System.out.println("course:"+course);

        // 如果没前段传了就默认page为1,size为100
        if (map.get("page") == null || map.get("size") == null) {
            coursePageInfo = courseService.selectTrueList(1, 100, course);

        }else {
            coursePageInfo = courseService.selectTrueList(Integer.valueOf(map.get("page").toString()), Integer.valueOf(map.get("size").toString()), course);
        }
        List<Course> list = coursePageInfo.getList();

        System.out.println("list:"+list);

        // 生成给前端返回的集合
        List<CourseForMain> myLoveCourse = new ArrayList<>();
        // 遍历并赋值
        if (map.get("uId") != null) {
            for (Course course1 : list) {
                // 将数组转移到新的对象上，主要是将等级和类型转成字符串反给前端
                CourseForMain courseForMain = new CourseForMain();
                courseForMain.setId(course1.getId());
                courseForMain.setExplain(course1.getExplain());
                courseForMain.setCover(course1.getCover());
                // 根据课程的等级id查询等级id
                Long lmId = course1.getLmId();
                LevelManager levelManager = levelManagerService.selectById(lmId);
                courseForMain.setLevel(levelManager.getLevel());
                // 根绝课程的类型id查询等级id
                Long typeId = course1.getTypeId();
                Type type = typeService.selectById(typeId);
                courseForMain.setType(type.getName());
                courseForMain.setTitle(course1.getTitle());
                // 遍历查看当前用户是否收藏该课程
                // 根据当前id获取用户的收藏的课程
                // 默认表示该用户没有收藏过了该课程
                courseForMain.setIsLove(0);
                List<Course> loveCourses = mainService.getLoveCourse(Long.valueOf(map.get("uId").toString()));
                for (Course loveCourse : loveCourses) {
                    // 获取用户收藏过的课程的id
                    Long loveId = loveCourse.getId();
                    // 如果课程id与收藏的课程的id相同，设置课程收藏状态为1
                    if (loveId.equals(course1.getId())) {
                        // 表示该用户已经收藏过了该课程
                        courseForMain.setIsLove(1);
                    }
                }

                // 根据条件做出判断
                // 将类型转化后存集合中
                myLoveCourse.add(courseForMain);
            }
        }
        long total = coursePageInfo.getTotal();
        if (list.size() == 0) {
            throw new BusinessException(ExceptionCode.WRONG_DATA);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        if (map.get("uId") != null) {
            jsonResult.setData(myLoveCourse);
        } else {
            jsonResult.setData(list);
        }

        jsonResult.put("count", total);
        return jsonResult.getDataMap();
    }

    @PostMapping("/update")
    @ApiOperation("修改课程的接口")
    @ApiImplicitParam(name = "course", value = "course", dataType = "Course", paramType = "body", dataTypeClass = Course.class)
    public Map<String, Object> update(@RequestBody Course course) throws BusinessException {

        if (course.getId() == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }

        Integer integer = courseService.updateById(course);

        if (integer == 0) {
            throw new BusinessException(ExceptionCode.WRONG_UPLOAD);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/delete")
    @ApiOperation("删除课程的接口")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Map", paramType = "body")
    public Map<String, Object> delete(@RequestBody Map<String, Object> id) throws BusinessException {

        if (id == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }

        Integer integer = courseService.deleteById(Long.valueOf(id.get("id").toString()));


        if (integer == 0) {
            throw new BusinessException(ExceptionCode.WRONG_DELETE);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/selectById")
    @ApiOperation("根据id查询课程的接口")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query")
    public Map<String, Object> selectById(@RequestParam Long id) throws BusinessException {

        PageHelper.startPage(1, 3);

        if (id == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }

        Course course = courseService.selectById(id);

        Course findCourse = new Course();
        findCourse.setTypeId(course.getTypeId());

        List<Course> select = courseService.select(findCourse);
        PageInfo<Course> of = PageInfo.of(select);
        List<Course> list = of.getList();

        Map<String, Object> map = new HashMap<>(16);
        if (course.getStatus() != null) {
            if (course.getStatus()) {
                Map<String, String> typeAndLevel = courseService.getTypeAndLevel(course.getId());
                map.put("id", course.getId());
                map.put("status", course.getStatus());
                map.put("title", course.getTitle());
                map.put("cover", course.getCover());
                map.put("type", typeAndLevel.get("type_name"));
                map.put("level", typeAndLevel.get("level_manager_level"));
                map.put("explain", course.getExplain());
            }
        }

        mainService.incrCourseScore(map);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        jsonResult.setData(list);
        return jsonResult.getDataMap();
    }

}
